/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 音乐播放页面 - MVVM 架构实现
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../viewmodels/music_player_view_model.dart';
import '../models/music_item_model.dart';
import '../models/play_mode.dart';
import '../utils/smart_color_generator.dart';
import '../services/floating_player_service.dart';
import 'playlist_page_view.dart';

/// 音乐播放页面
/// 完全复制原项目的UI设计和交互效果
class MusicPlayerPage extends StatefulWidget {
  /// 音乐数据（可选，如果不提供则使用当前播放的音乐）
  final MusicItemModel? music;

  /// 是否显示实时进度（用于播放列表页面的区分）
  final bool showRealTimeProgress;

  /// 是否是当前播放的音乐
  final bool isCurrentPlaying;

  /// 初始音乐（用于路由传参）
  final MusicItemModel? initialMusic;

  /// 是否自动播放
  final bool autoPlay;

  const MusicPlayerPage({
    super.key,
    this.music,
    this.showRealTimeProgress = true,
    this.isCurrentPlaying = true,
    this.initialMusic,
    this.autoPlay = false,
  });

  @override
  State<MusicPlayerPage> createState() => _MusicPlayerPageState();
}

class _MusicPlayerPageState extends State<MusicPlayerPage>
    with PlayerPageMixin {
  /// 背景渐变色列表
  List<Color> _gradientColors = [
    Colors.black,
    Colors.black,
  ];

  @override
  void initState() {
    super.initState();
    _updateGradientColors();

    // 处理初始音乐和自动播放
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _handleInitialMusic();
    });
  }

  /// 处理初始音乐和自动播放
  void _handleInitialMusic() {
    if (widget.initialMusic != null) {
      final viewModel = context.read<MusicPlayerViewModel>();

      // 如果需要自动播放
      if (widget.autoPlay) {
        viewModel.play(widget.initialMusic!);
      } else {
        // 设置播放列表但不播放
        viewModel.setPlaylist([widget.initialMusic!]);
      }
    }
  }

  @override
  void didUpdateWidget(MusicPlayerPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.music != widget.music) {
      _updateGradientColors();
    }
  }

  /// 更新背景渐变色
  Future<void> _updateGradientColors() async {
    final music =
        widget.music ?? context.read<MusicPlayerViewModel>().currentTrack;
    if (music?.albumArt != null && music!.albumArt!.isNotEmpty) {
      try {
        final colors = await SmartColorGenerator.generateGradientFromImage(
          music.albumArt!,
          fallbackColor: Colors.black,
        );
        if (mounted) {
          setState(() {
            _gradientColors = colors;
          });
        }
      } catch (e) {
        // 如果获取颜色失败，使用默认颜色
        if (mounted) {
          setState(() {
            _gradientColors = [Colors.black, Colors.black];
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: _gradientColors,
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: Stack(
          children: [
            // 主要内容
            SafeArea(
              child: Column(
                children: [
                  const SizedBox(height: kToolbarHeight + 20),
                  // 专辑封面
                  _buildAlbumCover(),
                  // 播放控制区域
                  Expanded(
                    child: _buildPlayerControls(),
                  ),
                  const SizedBox(height: 10),
                ],
              ),
            ),
            // 自定义 AppBar
            _buildCustomAppBar(),
          ],
        ),
      ),
    );
  }

  /// 构建自定义 AppBar
  Widget _buildCustomAppBar() {
    return Positioned(
      left: 0,
      right: 0,
      top: 0,
      child: SafeArea(
        child: Container(
          height: kToolbarHeight,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              IconButton(
                icon: const Icon(
                  Icons.close_rounded,
                  color: Colors.white,
                  size: 28,
                ),
                onPressed: () => Navigator.of(context).pop(),
              ),
              const Spacer(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建专辑封面
  Widget _buildAlbumCover() {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        final music = widget.music ?? viewModel.currentTrack;
        final screenWidth = MediaQuery.of(context).size.width;
        final imageSize = screenWidth - 40;

        return Container(
          width: imageSize,
          height: imageSize,
          margin: const EdgeInsets.symmetric(horizontal: 20),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 20,
                offset: const Offset(0, 10),
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: music?.albumArt != null && music!.albumArt!.isNotEmpty
                ? CachedNetworkImage(
                    imageUrl: music.albumArt!,
                    fit: BoxFit.cover,
                    placeholder: (context, url) =>
                        _buildAlbumPlaceholder(music),
                    errorWidget: (context, url, error) =>
                        _buildAlbumPlaceholder(music),
                  )
                : _buildAlbumPlaceholder(music),
          ),
        );
      },
    );
  }

  /// 构建专辑封面占位符
  Widget _buildAlbumPlaceholder(MusicItemModel? music) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(10),
      ),
      child: Center(
        child: music != null
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.music_note,
                    color: Colors.white,
                    size: 80,
                  ),
                  const SizedBox(height: 16),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: Text(
                      music.title,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              )
            : const Icon(
                Icons.music_note,
                color: Colors.white,
                size: 80,
              ),
      ),
    );
  }

  /// 构建播放控制区域
  Widget _buildPlayerControls() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        // 歌曲信息
        _buildSongInfo(),
        const SizedBox(height: 30),
        // 进度条和时间
        _buildProgressSection(),
        const SizedBox(height: 30),
        // 播放控制按钮
        _buildPlaybackControls(),
        const SizedBox(height: 20),
      ],
    );
  }

  /// 构建歌曲信息
  Widget _buildSongInfo() {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        final music = widget.music ?? viewModel.currentTrack;

        if (music == null) {
          return const Padding(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '暂无播放内容',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 6),
                Text(
                  '请选择音乐开始播放',
                  style: TextStyle(
                    color: Colors.white70,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          );
        }

        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                music.title,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 6),
              Text(
                music.artist,
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 14,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建进度条部分
  Widget _buildProgressSection() {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        final music = widget.music ?? viewModel.currentTrack;

        if (music == null) {
          return const SizedBox.shrink();
        }

        // 如果是当前播放的音乐且需要显示实时进度
        if (widget.isCurrentPlaying && widget.showRealTimeProgress) {
          return _buildRealTimeProgress(viewModel);
        } else {
          // 静态进度条（非当前播放或不需要实时更新）
          return _buildStaticProgress(music, viewModel);
        }
      },
    );
  }

  /// 构建实时进度条
  Widget _buildRealTimeProgress(MusicPlayerViewModel viewModel) {
    return Column(
      children: [
        // 进度条
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: ValueListenableBuilder<Duration>(
            valueListenable: viewModel.position,
            builder: (context, position, child) {
              return ValueListenableBuilder<Duration>(
                valueListenable: viewModel.duration,
                builder: (context, duration, child) {
                  final progress = duration.inMilliseconds > 0
                      ? position.inMilliseconds / duration.inMilliseconds
                      : 0.0;

                  return SliderTheme(
                    data: SliderTheme.of(context).copyWith(
                      trackHeight: 2,
                      thumbShape: const RoundSliderThumbShape(
                        enabledThumbRadius: 6,
                      ),
                      overlayShape: const RoundSliderOverlayShape(
                        overlayRadius: 12,
                      ),
                      activeTrackColor: Colors.white,
                      inactiveTrackColor: Colors.white30,
                      thumbColor: Colors.white,
                    ),
                    child: Slider(
                      value: progress.clamp(0.0, 1.0),
                      onChanged: (value) {
                        final seekPosition = Duration(
                          milliseconds:
                              (duration.inMilliseconds * value).round(),
                        );
                        viewModel.seekTo(seekPosition);
                      },
                    ),
                  );
                },
              );
            },
          ),
        ),
        // 时间标签
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: ValueListenableBuilder<Duration>(
            valueListenable: viewModel.position,
            builder: (context, position, child) {
              return ValueListenableBuilder<Duration>(
                valueListenable: viewModel.duration,
                builder: (context, duration, child) {
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        _formatDuration(position),
                        style: const TextStyle(
                          color: Colors.white70,
                          fontSize: 12,
                        ),
                      ),
                      Text(
                        _formatDuration(duration),
                        style: const TextStyle(
                          color: Colors.white70,
                          fontSize: 12,
                        ),
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ),
      ],
    );
  }

  /// 构建静态进度条
  Widget _buildStaticProgress(
      MusicItemModel music, MusicPlayerViewModel viewModel) {
    return Column(
      children: [
        // 静态进度条
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: SliderTheme(
            data: SliderTheme.of(context).copyWith(
              trackHeight: 2,
              thumbShape: const RoundSliderThumbShape(
                enabledThumbRadius: 6,
              ),
              overlayShape: const RoundSliderOverlayShape(
                overlayRadius: 12,
              ),
              activeTrackColor: Colors.white,
              inactiveTrackColor: Colors.white30,
              thumbColor: Colors.white,
            ),
            child: Slider(
              value: 0.0,
              onChanged: (value) {
                // 点击静态进度条时切换到该音乐并播放
                if (music != viewModel.currentTrack) {
                  viewModel.play(music);
                }
              },
            ),
          ),
        ),
        // 静态时间标签
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '00:00',
                style: TextStyle(
                  color: Colors.white70,
                  fontSize: 12,
                ),
              ),
              Text(
                _formatDuration(music.duration ?? Duration.zero),
                style: const TextStyle(
                  color: Colors.white70,
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建播放控制按钮
  Widget _buildPlaybackControls() {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 播放模式按钮
            ValueListenableBuilder(
              valueListenable: viewModel.playMode,
              builder: (context, playMode, child) {
                return IconButton(
                  icon: Icon(
                    playMode.icon,
                    color: Colors.white,
                    size: 30,
                  ),
                  onPressed: viewModel.togglePlayMode,
                );
              },
            ),

            const SizedBox(width: 40),

            // 播放/暂停按钮
            _buildMainPlayButton(viewModel),

            const SizedBox(width: 40),

            // 播放列表按钮
            Stack(
              children: [
                IconButton(
                  icon: const Icon(
                    Icons.queue_music_rounded,
                    color: Colors.white,
                    size: 30,
                  ),
                  onPressed: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) => const PlaylistPageView(),
                      ),
                    );
                  },
                ),
                // 播放列表数量标识
                if (viewModel.playlist.isNotEmpty)
                  Positioned(
                    right: 4,
                    top: 2,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 4),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(100),
                      ),
                      child: Text(
                        '${viewModel.playlist.length}',
                        style: const TextStyle(
                          fontSize: 10,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ],
        );
      },
    );
  }

  /// 构建主播放按钮
  Widget _buildMainPlayButton(MusicPlayerViewModel viewModel) {
    return ValueListenableBuilder<bool>(
      valueListenable: viewModel.isPlaying,
      builder: (context, isPlaying, child) {
        return Container(
          width: 60,
          height: 60,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
              color: Colors.white,
              width: 1,
            ),
          ),
          child: Stack(
            alignment: Alignment.center,
            children: [
              // 加载指示器
              if (viewModel.isLoading)
                const SizedBox(
                  width: 60,
                  height: 60,
                  child: CircularProgressIndicator(
                    strokeWidth: 1,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                ),
              // 播放/暂停图标
              IconButton(
                icon: AnimatedSwitcher(
                  duration: const Duration(milliseconds: 200),
                  child: Icon(
                    isPlaying ? Icons.pause : Icons.play_arrow,
                    key: ValueKey(isPlaying),
                    color: Colors.white,
                    size: 30,
                  ),
                ),
                onPressed:
                    viewModel.isLoading ? null : viewModel.togglePlayPause,
              ),
            ],
          ),
        );
      },
    );
  }

  /// 格式化时长显示
  String _formatDuration(Duration duration) {
    final minutes = duration.inMinutes;
    final seconds = duration.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
}
